package com.paas.form.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bpm.feign.model.BpmDeCategoryEntity;
import com.bpm.feign.model.ProcessCmd;
import com.bpm.feign.service.IBpmDeCategoryService;
import com.bpm.feign.service.IBpmDeModelService;
import com.bpm.feign.service.IBpmProcessInstanceService;
import com.paas.common.model.BaseUserInfo;
import com.paas.common.model.RestResponse;
import com.paas.common.util.BeanUtil;
import com.paas.common.util.ListUtil;
import com.paas.common.util.StringUtil;
import com.paas.common.util.UniqueIdUtil;
import com.paas.common.web.SystemConst;
import com.paas.common.web.annotion.OperLog;
import com.paas.common.web.controller.BaseController;
import com.paas.common.web.oper.OprLogConstant;
import com.paas.form.constant.FormConstant;
import com.paas.form.dto.FormViewPublishDto;
import com.paas.form.entity.*;
import com.paas.form.service.*;
import com.paas.form.vo.FormViewVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/form/formDefinition")
@Api(description = "视图模块", tags = "")
public class FormDefinitionController extends BaseController {

    @Autowired
    public IFormDefinitionService formDefinitionService;

    @Autowired
    public IFormViewPublishApprovalService formViewPublishApprovalService;

    @Autowired
    public IBpmProcessInstanceService bpmProcessInstanceService;

    @Autowired
    public IBpmDeModelService bpmDeModelService;

    @Autowired
    public IBpmDeCategoryService bpmDeCategoryService;

    @Autowired
    public IFormViewPubService formViewPubService;

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @OperLog(operType = OprLogConstant.ADD, operModul = "", operDescribe = "保存")
    public void save(@RequestBody FormDefinitionEntity formViewPublishEntity) throws ParseException {
        BaseUserInfo baseUserInfo = getUserInfo();

        if (BeanUtil.isNotEmpty(formViewPublishEntity)) {
            injectUpdateDataAuth(formViewPublishEntity);
            formViewPublishEntity.setStatus(SystemConst.NORMAL_STATUS);
            formViewPublishEntity.setCreateId(baseUserInfo.getUserId());
            formViewPublishEntity.setModifyId(baseUserInfo.getUserId());
            formViewPublishEntity.setPublishApprovalStatus("1");
        }
        formDefinitionService.save(formViewPublishEntity);
    }

    /**
     * 集成工作流
     * @param formViewPublishDto
     * @return
     */
    @PostMapping(value = "/saveFormViewPublish")
    @ApiOperation(value = "保存信息", notes = "保存信息")
    @ResponseBody
    public RestResponse saveFormViewPublish(@RequestBody FormViewPublishDto<ProcessCmd> formViewPublishDto) {
        try {
            if(BeanUtil.isEmpty(formViewPublishDto) || BeanUtil.isEmpty(formViewPublishDto.getFormViewPublishEntity())){
                return RestResponse.error("保存失败,表单信息为空");
            }
            BaseUserInfo baseUserInfo = getUserInfo();
            // 视图表单信息
            FormDefinitionEntity formViewPublishEntity = formViewPublishDto.getFormViewPublishEntity();
            // 流程信息
            ProcessCmd processCmd = formViewPublishDto.getProcessCmd();
            if (StringUtil.isEmpty(formViewPublishEntity.getId())) {
                List<String> bizStatus = new ArrayList<>();
                bizStatus.add(FormDefinitionEntity.BIZ_STATUS_SUBMIT);
                bizStatus.add(FormDefinitionEntity.BIZ_STATUS_REJECT);
                bizStatus.add(FormDefinitionEntity.BIZ_STATUS_APPROVAL);

                boolean flag = formDefinitionService.isExistsForm(formViewPublishEntity.getViewId(),bizStatus);
                if(flag){
                    return RestResponse.error("保存失败,当前视图存在已发布的表单");
                }
                formViewPublishEntity.setId(UniqueIdUtil.getIntGuid());
                if (BeanUtil.isNotEmpty(processCmd)) {
                    processCmd.setBusinessKey(formViewPublishEntity.getId());
                    processCmd.setData(JSON.toJSONString(formViewPublishEntity));
                    processCmd.setAppId(baseUserInfo.getAppId());
                    bpmProcessInstanceService.startProcessInstance(processCmd);
                }
                formViewPublishEntity.setStatus(SystemConst.NORMAL_STATUS);
                formViewPublishEntity.setPublishApprovalStatus(SystemConst.NORMAL_STATUS);
                formViewPublishEntity.setOrgId(baseUserInfo.getOrgId());
                formDefinitionService.insert(formViewPublishEntity);
            } else {
                processCmd.setToEditor(true);
                processCmd.setData(JSON.toJSONString(formViewPublishEntity));
                bpmProcessInstanceService.completeSubmitTask(processCmd);
                // 修改数据
                formDefinitionService.save(formViewPublishEntity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return RestResponse.error("保存失败");
        }
        return RestResponse.success();
    }

    @RequestMapping(value = "/delectById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id删除数据", notes = "根据Id删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-删除")
    public void delectById(String id) {
        if (null != id && !"".equals(id)) {
            FormDefinitionEntity formViewPublishEntity = new FormDefinitionEntity();
            injectUpdateDataAuth(formViewPublishEntity);
            formViewPublishEntity.setId(id);
            formDefinitionService.deleteByEntity(formViewPublishEntity);
        }
    }

    @RequestMapping(value = "/deleteBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id批量删除数据", notes = "根据Id批量删除数据")
    @OperLog(operType = OprLogConstant.DELETE, operModul = "", operDescribe = "-批量删除")
    public void deleteBatchByIds(@RequestBody List<String> ids) {
        if (null != ids && ids.size() > 0) {
            FormDefinitionEntity formViewPublishEntity = new FormDefinitionEntity();
            injectUpdateDataAuth(formViewPublishEntity);
            //formViewPublishService.deleteBatchIds(ids);
            formDefinitionService.deleteBatchIdsWithPermission(ids, formViewPublishEntity);
        }
    }

    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    @ApiOperation(value = "根据Id查询对象", notes = "根据Id查询对象")
    public FormDefinitionEntity queryById(String id) {
        FormDefinitionEntity bean = null;
        if (StringUtil.isNotEmpty(id)) {
            bean = formDefinitionService.getById(id);
        }
        return bean;
    }

    /**
     * 查询表单明细 含流程分类名称转换
     * @param id
     * @return
     */
    @RequestMapping(value = "/getFormWithBpmById", method = RequestMethod.GET)
    @ApiOperation(value = "查询表单明细", notes = "查询表单明细")
    public FormDefinitionEntity getFormWithBpmById(String id) {
        FormDefinitionEntity formDefinitionEntity = null;
        if (StringUtil.isNotEmpty(id)) {
            formDefinitionEntity = formDefinitionService.getById(id);
            /**
             * 处理流程分类名称
             */
            if("1".equals(formDefinitionEntity.getIsProcess())){
                List<String> processIds = new ArrayList<>();
                if(StringUtil.isNotEmpty(formDefinitionEntity.getApplyProcess())){
                    ListUtil.addUniqueValue(processIds,formDefinitionEntity.getApplyProcess());
                }
                if(StringUtil.isNotEmpty(formDefinitionEntity.getChangeProcess())){
                    ListUtil.addUniqueValue(processIds,formDefinitionEntity.getChangeProcess());
                }
                if(StringUtil.isNotEmpty(formDefinitionEntity.getDeleteProcess())){
                    ListUtil.addUniqueValue(processIds,formDefinitionEntity.getDeleteProcess());
                }
                if(StringUtil.isNotEmpty(formDefinitionEntity.getEnableProcess())){
                    ListUtil.addUniqueValue(processIds,formDefinitionEntity.getEnableProcess());
                }
                if(StringUtil.isNotEmpty(formDefinitionEntity.getStopProcess())){
                    ListUtil.addUniqueValue(processIds,formDefinitionEntity.getStopProcess());
                }
                //定义key为流程分类id,value为流程分类对象
                Map<String, BpmDeCategoryEntity> bpmDeCategoryMap = new HashMap<String,BpmDeCategoryEntity>();
                if(BeanUtil.isNotEmpty(processIds)){
                    List<BpmDeCategoryEntity> bpmDeCategoryList = bpmDeCategoryService.queryBatchByIds(processIds);
                    if(bpmDeCategoryList!=null){
                        bpmDeCategoryMap = bpmDeCategoryList.stream().collect(Collectors.toMap(BpmDeCategoryEntity::getId, item ->item));
                    }
                }
                if(bpmDeCategoryMap!=null){
                    //设置开启流程分类名称
                    if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getApplyProcess())){
                        formDefinitionEntity.setApplyProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getApplyProcess()).getCatgName());
                    }
                    if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getChangeProcess())){
                        formDefinitionEntity.setChangeProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getChangeProcess()).getCatgName());
                    }

                    if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getDeleteProcess())){
                        formDefinitionEntity.setDeleteProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getDeleteProcess()).getCatgName());
                    }

                    if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getStopProcess())){
                        formDefinitionEntity.setStopProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getStopProcess()).getCatgName());
                    }

                    if(bpmDeCategoryMap.containsKey(formDefinitionEntity.getEnableProcess())){
                        formDefinitionEntity.setEnableProcessName(bpmDeCategoryMap.get(formDefinitionEntity.getEnableProcess()).getCatgName());
                    }
                }

            }
        }
        return formDefinitionEntity;
    }


    @RequestMapping(value = "/getFormDetailById", method = RequestMethod.GET)
    @ApiOperation(value = "查询表单明细", notes = "查询表单明细")
    public FormViewVo getFormDetailById(String id) {
        FormViewVo formViewVo = new FormViewVo();
        if (StringUtil.isNotEmpty(id)) {
            formViewVo = formDefinitionService.getFormDetailById(id);
        }
        return formViewVo;
    }

    @RequestMapping(value = "/queryBatchByIds", method = RequestMethod.POST)
    @ApiOperation(value = "根据Id查询对象列表", notes = "根据Id查询对象列表")
    public List<FormDefinitionEntity> queryBatchByIds(@RequestBody List<String> ids) {
        List<FormDefinitionEntity> list = formDefinitionService.getBatchByIds(ids);
        return list;
    }

    @RequestMapping(value = "/queryPage", method = RequestMethod.GET)
    @ApiOperation(value = "模板分页查询", notes = "模板分页查询")
    public IPage<FormDefinitionEntity> queryPage(FormDefinitionEntity formViewPublishEntity, Integer currentPage, Integer pageSize) {
        if (currentPage == null) {
            currentPage = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        injectCheckDataAuth(formViewPublishEntity);
        IPage<FormDefinitionEntity> pageBean = formDefinitionService.getFormViewPage(formViewPublishEntity, currentPage, pageSize);
        return pageBean;
    }

    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    @ApiOperation(value = "模板查询", notes = "模板查询")
    public List<FormDefinitionEntity> queryList(FormDefinitionEntity formViewPublishEntity) {
        injectCheckDataAuth(formViewPublishEntity);
        List<FormDefinitionEntity> list = formDefinitionService.getList(formViewPublishEntity);
        return list;
    }

    @RequestMapping(value = "/agreeApproval", method = RequestMethod.POST)
    @ApiOperation(value = "同意申请", notes = "同意申请")
    public RestResponse agreeApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormDefinitionEntity formViewPublishEntity = formDefinitionService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formViewPublishEntity)) {
                formViewPublishEntity.setPublishApprovalStatus(FormDefinitionEntity.BIZ_STATUS_APPROVAL);
                formDefinitionService.updateById(formViewPublishEntity);

                //更新运行视图状态至已发布
                FormViewPubEntity formViewPubBean = formViewPubService.getById(formViewPublishEntity.getViewId());


                FormViewPubEntity formViewPubEntity = new FormViewPubEntity();
                formViewPubEntity.setId(formViewPublishEntity.getViewId());
                if(StringUtil.isNotEmpty(formViewPubBean.getBizStatus())){
                    if("30".equals(formViewPubBean.getBizStatus())||"35".equals(formViewPubBean.getBizStatus())){
                        formViewPubEntity.setBizStatus("35");
                    }else {
                        formViewPubEntity.setBizStatus("50");
                    }
                }else {
                    formViewPubEntity.setBizStatus("50");
                }
                formViewPubService.updateById(formViewPubEntity);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }

    @RequestMapping(value = "/refuseApproval", method = RequestMethod.POST)
    @ApiOperation(value = "审核反对", notes = "审核反对")
    public RestResponse refuseApproval(String bussinessKey) {
        if (StringUtil.isNotEmpty(bussinessKey)) {
            FormDefinitionEntity formViewPublishEntity = formDefinitionService.getById(bussinessKey);
            if (BeanUtil.isNotEmpty(formViewPublishEntity)) {
                formViewPublishEntity.setPublishApprovalStatus(FormDefinitionEntity.BIZ_STATUS_CANCAL);
                formDefinitionService.updateById(formViewPublishEntity);
                return RestResponse.success();
            }
        }
        return RestResponse.error();
    }
}